package com.yeyks.task;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeyks.common.constants.ConfigKey;
import com.yeyks.common.em.OrderStatusEnum;
import com.yeyks.common.utils.DateUtils;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.commonReference.service.order.OrderHeadService;
import com.yeyks.order.dal.domain.OrderHead;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 修改订单状态为入住中(每天18点零1和零3执行)
 *
 * @author shuai
 * @date 2019/10/28 13:28
 */
@Component
@Slf4j
public class OrderCheckInTask {
    @Autowired
    private OrderHeadService orderHeadService;
    @Autowired
    private ConfigService configService;

    @Scheduled(cron = "${schedule.order.checkIn}")
    private void orderCheckInTask() {
        log.info("订单入住中执行-----------，time = {}", DateUtil.formatDateTime(new Date()));
        //查询出来所有待入住和待退款的订单（2,5）
        List<OrderHead> orderHeads = orderHeadService.list(new QueryWrapper<OrderHead>()
                .in(OrderHead.STATUS, OrderStatusEnum.PRECHECKIN.value(),OrderStatusEnum.toBeConfirmed.value()));
        if (orderHeads == null || orderHeads.size() == 0) {
            log.info("查询到的待入住和待退款的订单数为空");
            return;
        }
        Date nowDate = new Date();
        //过滤离店时间后12个小时大于当前时间的订单
        List<OrderHead> disposeOrderHeads = orderHeads.stream().filter(e -> DateUtils.dateCompareDate(DateUtils.afterHoursToDate(e.getCheckOut(), 12L), nowDate)).collect(Collectors.toList());
        for (OrderHead orderHead : disposeOrderHeads) {
            Date date = DateUtils.afterHoursToDate(orderHead.getCheckIn(), Long.valueOf(getCheckInHour()));
            if (DateUtils.dateCompareDate(nowDate, date)) {
                //修改订单状态为入住中
                orderHead.setStatus(OrderStatusEnum.LIVING.value());
                if (orderHeadService.updateById(orderHead)) {
                    log.info("修改订单状态为入住中成功{}", orderHead.getOrderNo());
                } else {
                    log.info("修改订单状态为入住中失败{}", orderHead.getOrderNo());
                }
            }
        }
        log.info("订单入住中执行end");
    }

    /**
     * 订单修改入住中的时间
     */
    private Integer getCheckInHour() {
        try {
            String value = configService.getValue(ConfigKey.ORDER_CHECKIN);
            JSONObject jsonObject = JSONObject.parseObject(value);
            return (Integer) jsonObject.get("checkin");
        } catch (Exception e) {
            log.error("查询订单checkIn失败{}", e.getLocalizedMessage());
            return 18;
        }
    }
}
